package org.example.springbook.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.example.springbook.constants.Constant;
import org.example.springbook.model.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("登录拦截器校验...");
        // 要进行登录校验 首先就要从Session中判断
        // 以下两种写法都可以
//        HttpSession session = request.getSession(false);
//        if (session != null && session.getAttribute(Constant.SESSION_USER_KEY) != null) {
//            UserInfo userInfo = (UserInfo) session.getAttribute(Constant.SESSION_USER_KEY);
//                if (userInfo!=null && userInfo.getId()>=0){
//                    return true;
//                }
//        }
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute(Constant.SESSION_USER_KEY);
        if (userInfo!=null && userInfo.getId()>=0){
            return true;
        }
        response.setStatus(401); // 表示用户未登录
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
